package com.qing.springbootinit.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qing.springbootinit.common.ErrorCode;
import com.qing.springbootinit.constant.ChatConstant;
import com.qing.springbootinit.exception.BusinessException;
import com.qing.springbootinit.manager.AiManager;
import com.qing.springbootinit.manager.DeepAiManger;
import com.qing.springbootinit.mapper.ChatmessagesMapper;
import com.qing.springbootinit.model.entity.ChatMessage;
import com.qing.springbootinit.model.entity.ChatMessages;
import com.qing.springbootinit.model.entity.ChatRoom;
import com.qing.springbootinit.model.entity.User;
import com.qing.springbootinit.model.enums.ChatMessageEnum;
import com.qing.springbootinit.service.ChatmessagesService;
import com.qing.springbootinit.service.ChatroomService;
import com.qing.springbootinit.service.UserService;

import io.github.briqt.spark4j.SparkClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author <a href="https://github.com/qingfengzy">qingfengzy</a>
* @description 针对表【chatmessages(聊天消息表)】的数据库操作Service实现
* @createDate 2025-04-29 20:50:06
*/
@Service
@Slf4j
public class ChatmessagesServiceImpl extends ServiceImpl<ChatmessagesMapper, ChatMessages>
    implements ChatmessagesService {
    private int MAX_SIZE = 5;

    long startTime = System.currentTimeMillis();  //每隔10min,自动写入数据库

    //存储历史记录
    private Map<String, List<ChatMessages>> chatMessageHistory = new HashMap<>();

    //批量写输入数据库
    List<ChatMessages> chatMessagesList = new ArrayList<>();

    @Resource
    private UserService userService;

    @Resource
    private ChatroomService chatroomService;
    @Resource
    private DeepAiManger deepAiManger;

    @Resource
    private AiManager aiManager;

    /**
     * AI对话核心方法 (内存存储版
     * @param request
     * @param roomId
     * @param userPrompt
     * @return
     */
    @Override
    public String doChatOFIM(HttpServletRequest request, String roomId, String userPrompt) {
        //准备消息关联上下文
//        首先是ai的样式
        final String SYSTEM_PROMPT = ChatConstant.SYSTEM_PROMPT;
//        然后是角色的建立
        final ChatMessage systemMessage = ChatMessage.builder().sender(ChatMessageEnum.SYSTEM.getValue()).content(SYSTEM_PROMPT).build();
        final ChatMessage userMessage = ChatMessage.builder()
                .sender(ChatMessageEnum.USER.getValue())
                .content(userPrompt)
                .build();
        //处理历史对话历史记录
//        看是否是第一次执行历史对话记录
        ChatMessages systemMessages = new ChatMessages(); // 初始化目标对象
        ChatMessages userMessages = new ChatMessages(); // 初始化目标对象
        BeanUtils.copyProperties(systemMessage,systemMessages);
        BeanUtils.copyProperties(userMessage,userMessages);
        List<ChatMessages> messages = new ArrayList<>();
        if(!"开始".equals(userPrompt) && chatMessageHistory.isEmpty()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请输入“开始”，开启游戏");
        }
        //第一次用户输入信息
        if("开始".equals(userPrompt)&& !chatMessageHistory.containsKey(roomId)){
            messages.add(systemMessages);
            chatMessageHistory.put(roomId,messages);
        }else {
//        第1+n次输入信息,添加历史记录
            messages = chatMessageHistory.get(roomId);
        }
        messages.add(userMessages);

        //调用AI
//        String response = aiManager.doChat(true,messages);
        String response = deepAiManger.doChatByAI(messages);
        //清除map缓存
        if(response.contains("【游戏已结束】"))
        {
            chatMessageHistory.remove(roomId);
        }

        return response;
    }

    /**
     * AI对话核心方法 (数据库存储版
     * @param request
     * @param roomId
     * @param userPrompt
     * @return
     */
    @Override
    public String doChatOfDB(HttpServletRequest request, String roomId, String userPrompt) {
        //准备消息关联上下文
        User loginUser = userService.getLoginUser(request);
        if(loginUser == null || loginUser.getId() == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        long userId = loginUser.getId();
//        首先是ai的样式
        final String SYSTEM_PROMPT = ChatConstant.SYSTEM_PROMPT;
//        然后是角色的建立
        final ChatMessage systemMessage = ChatMessage.builder().sender(ChatMessageEnum.SYSTEM.getValue()).content(SYSTEM_PROMPT).build();
        final ChatMessage userMessage = ChatMessage.builder()
                .sender(ChatMessageEnum.USER.getValue())
                .content(userPrompt)
                .build();
        //处理历史对话历史记录
        ChatMessages systemMessages = new ChatMessages(); // 初始化目标对象
        ChatMessages userMessages = new ChatMessages(); // 初始化目标对象
        BeanUtils.copyProperties(systemMessage,systemMessages);
        BeanUtils.copyProperties(userMessage,userMessages);
        List<ChatMessages> messages = new ArrayList<>();

        LambdaQueryWrapper<ChatMessages> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatMessages::getRoomId,roomId);
        List<ChatMessages> list = this.list(queryWrapper);
//        看是否是第一次执行历史对话记录
//        List<ChatMessages> messages = new ArrayList<>();
//        if(!"开始".equals(userPrompt) && chatMessageHistory.isEmpty()){
//            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请输入“开始”，开启游戏");
//        }
//        //第一次用户输入信息
//        if("开始".equals(userPrompt)&& !chatMessageHistory.containsKey(roomId)){
//            messages.add(systemMessages);
//            chatMessageHistory.put(roomId,messages);
//        }else {
////        第1+n次输入信息,添加历史记录
//            messages = chatMessageHistory.get(roomId);
//        }
//        messages.add(userMessages);
        if(!"开始".equals(userPrompt.trim()) && chatMessageHistory.isEmpty()){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请输入“开始”，开启游戏");
        }
        //第一次用户输入信息
        if("开始".equals(userPrompt) && list.isEmpty()){
            messages.add(systemMessages);
            chatMessageHistory.put(roomId,messages);

        }else{
//            第1+n次输入信息,添加历史记录
            messages = chatMessageHistory.get(roomId);
        }
        messages.add(userMessages);

        //调用AI
//        String response = deepAiManger.doChatByAI(messages);
        String response = aiManager.doChatByAI(messages);

        //第一次用户输入信息
        if("开始".equals(userPrompt) && list().isEmpty()){
            ChatRoom chatRoom =new ChatRoom();
//            chatRoom.setId(Long.valueOf(roomId));
            if (roomId != null) {
                chatRoom.setId(Long.valueOf(roomId)); // 检查roomId是否为null
            } else {
                // 处理roomId为null的情况，例如抛出业务异常或赋予默认值
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "roomId不能为null");
            }
            chatRoom.setStatus(0);
            chatRoom.setUserId(userId);
            chatRoom.setRoomBrief(response);
            chatroomService.save(chatRoom);
        }
//        final ChatMessage assistantMessage = ChatMessage.builder()
//                .
            //每次请求存储用户 和 AI的消息
            ChatMessages chatMessageUser = new ChatMessages();
//            chatMessageUser.setId();
            chatMessageUser.setRoomId(roomId);
            chatMessageUser.setSender(ChatMessageEnum.USER);
            chatMessageUser.setContent(userPrompt);
            ChatMessages charMessageAI = new ChatMessages();
            charMessageAI.setRoomId(roomId);
            charMessageAI.setContent(response);
            charMessageAI.setSender(ChatMessageEnum.AI);

            chatMessagesList.add(chatMessageUser);
            chatMessagesList.add(charMessageAI);

        //当消息存储到一定阈值 或者 会话超时 或者，游戏结束 则开始批量存入数据库，
        if(chatMessagesList.size()> MAX_SIZE || isTimeout(startTime)|| response.contains("【游戏已结束】")){
            if(!this.saveBatch(chatMessagesList)) {
                log.info("消息保存失败");
                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
            }

            //重置会话开始时间
            startTime =System.currentTimeMillis();
            chatMessagesList.clear();
        }
            //清除map缓存
            if(response.contains("【游戏已结束】"))
            {
                chatMessageHistory.remove(roomId);
                //设置房间状态
                ChatRoom chatRoom = new ChatRoom();
                chatRoom.setId(Long.parseLong(roomId));
                chatRoom.setStatus(0);
                chatroomService.updateById(chatRoom);
            }
        return response;
    }
    public boolean isTimeout(long startTime){
        long timeOut = 1000 * 10 * 60L; //10min
        if(System.currentTimeMillis() - startTime > timeOut){
            log.error("会话超时,消息自动存入数据库");
            return true;
        }
        return false;
    }
    // 重构：避免直接调用 chatmessagesService

}






